<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="login-bg">
      <view class="bg-shape shape1"></view>
      <view class="bg-shape shape2"></view>
      <view class="bg-shape shape3"></view>
    </view>

    <scroll-view scroll-y class="login-content">
      <!-- Logo和标题 -->
      <view
        class="logo-section text-center"
        :style="[{ animation: 'fadeInUp 0.8s ease-out' }]"
      >
        <view class="logo-wrapper">
          <image
            src="/static/images/logo.png"
            mode="aspectFit"
            class="app-logo"
          ></image>
        </view>
        <view class="app-title">万科门窗ERP</view>
        <view class="app-subtitle">员工移动工作平台</view>
      </view>

      <!-- 登录表单 -->
      <view class="login-form">
        <!-- 登录类型选择 -->
        <view class="login-type-tabs margin-bottom-lg">
          <view class="tabs-container">
            <view
              class="tab-item"
              :class="{ active: loginForm.loginType === 'admin' }"
              @click="switchLoginType('admin')"
            >
              <text class="tab-text">管理员登录</text>
            </view>
            <view
              class="tab-item"
              :class="{ active: loginForm.loginType === 'employee' }"
              @click="switchLoginType('employee')"
            >
              <text class="tab-text">员工登录</text>
            </view>
          </view>
        </view>

        <view class="form-content">
          <view class="input-group">
            <view class="input-wrapper">
              <text class="cuIcon-people input-icon"></text>
              <input
                class="form-input"
                :placeholder="
                  loginForm.loginType === 'employee'
                    ? '请输入员工编号'
                    : '请输入用户名'
                "
                v-model="loginForm.username"
                @input="clearError"
              />
            </view>
          </view>

          <view class="input-group">
            <view class="input-wrapper">
              <text class="cuIcon-lock input-icon"></text>
              <input
                class="form-input"
                placeholder="请输入密码"
                :password="!showPassword"
                v-model="loginForm.password"
                @input="clearError"
              />
              <text
                class="password-toggle"
                :class="[
                  showPassword ? 'cuIcon-attention' : 'cuIcon-attentionforbid',
                ]"
                @click="togglePassword"
              ></text>
            </view>
          </view>

          <view v-if="errorMessage" class="error-message">
            <text class="cuIcon-warn"></text>
            <text class="error-text">{{ errorMessage }}</text>
          </view>

          <button
            class="login-btn"
            :class="{ loading: loading }"
            :disabled="loading || !canLogin"
            @click="handleLogin"
          >
            <text v-if="loading" class="cuIcon-loading2 cuIconfont-spin"></text>
            <text>{{ loading ? "登录中..." : "登录" }}</text>
          </button>
        </view>
      </view>

      <!-- 版本信息 -->
      <!-- #ifdef APP-PLUS -->
      <view class="version-info text-center">
        <text class="version-text">版本 {{ version }}</text>
      </view>
      <!-- #endif -->
    </scroll-view>
  </view>
</template>

<script>
import authService from "../../src/services/auth.js";
import { http } from "../../common/service/service.js";
import { ACCESS_TOKEN, USER_INFO } from "@/common/util/constants.js";

export default {
  data() {
    return {
      loading: false,
      showPassword: false,
      errorMessage: "",
      version: "",
      loginForm: {
        username: "",
        password: "",
        loginType: "employee", // 默认员工登录
      },
    };
  },

  computed: {
    canLogin() {
      return this.loginForm.username.trim() && this.loginForm.password.trim();
    },
  },

  onLoad() {
    // #ifdef APP-PLUS
    const that = this;
    plus.runtime.getProperty(plus.runtime.appid, function (wgtinfo) {
      that.version = wgtinfo.version;
    });
    // #endif

    // 检查是否已登录
    if (authService.isLoggedIn()) {
      uni.reLaunch({
        url: "/pages/home/index",
      });
    }
  },

  methods: {
    switchLoginType(type) {
      this.loginForm.loginType = type;
      this.clearError();
      // 清空表单
      this.loginForm.username = "";
      this.loginForm.password = "";
    },

    async handleLogin() {
      if (this.loading) return;

      const usernameLabel =
        this.loginForm.loginType === "employee" ? "员工编号" : "用户名";

      if (!this.loginForm.username.trim()) {
        this.showError(`请输入${usernameLabel}`);
        return;
      }

      if (!this.loginForm.password.trim()) {
        this.showError("请输入密码");
        return;
      }

      this.loading = true;
      this.clearError();

      try {
        let result;

        if (this.loginForm.loginType === "employee") {
          // 员工登录
          result = await this.employeeLogin();
        } else {
          // 管理员登录
          result = await this.adminLogin();
        }

        if (result.success) {
          uni.showToast({
            title: "登录成功",
            icon: "success",
          });

          // 跳转到首页 - 使用reLaunch因为需要清除登录页面栈
          uni.reLaunch({
            url: "/pages/home/index",
          });
        } else {
          this.showError(result.message || "登录失败");
        }
      } catch (error) {
        console.error("登录失败:", error);
        this.showError("网络错误，请重试");
      } finally {
        this.loading = false;
      }
    },

    async adminLogin() {
      // 调用管理员登录接口
      const response = await http.post("/sys/mLogin", {
        username: this.loginForm.username,
        password: this.loginForm.password,
      });

      const responseData = response.data;
      if (responseData.success) {
        const { token, userInfo } = responseData.result;

        // 存储token和用户信息
        uni.setStorageSync(ACCESS_TOKEN, token);
        uni.setStorageSync(USER_INFO, userInfo);
        uni.setStorageSync("erp_login_type", "admin");

        // 更新认证服务中的用户信息
        authService.setUserInfo(userInfo);

        return {
          success: true,
          data: userInfo,
        };
      } else {
        return {
          success: false,
          message: responseData.message || "管理员登录失败",
        };
      }
    },

    async employeeLogin() {
      // 调用员工登录接口
      const response = await http.post("/sys/employeeLogin/mEmployeeLogin", {
        empNo: this.loginForm.username,
        password: this.loginForm.password,
      });

      const responseData = response.data;
      if (responseData.success) {
        const { token, userInfo } = responseData.result;

        // 存储token和用户信息
        uni.setStorageSync(ACCESS_TOKEN, token);
        uni.setStorageSync(USER_INFO, userInfo);
        uni.setStorageSync("erp_login_type", "employee");

        // 更新认证服务中的用户信息
        authService.setUserInfo(userInfo);

        return {
          success: true,
          data: userInfo,
        };
      } else {
        return {
          success: false,
          message: responseData.message || "员工登录失败",
        };
      }
    },

    togglePassword() {
      this.showPassword = !this.showPassword;
    },

    showError(message) {
      this.errorMessage = message;
    },

    clearError() {
      this.errorMessage = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;

  .bg-shape {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);

    &.shape1 {
      width: 300rpx;
      height: 300rpx;
      top: -150rpx;
      right: -150rpx;
    }

    &.shape2 {
      width: 200rpx;
      height: 200rpx;
      bottom: 200rpx;
      left: -100rpx;
    }

    &.shape3 {
      width: 150rpx;
      height: 150rpx;
      top: 300rpx;
      left: 50rpx;
    }
  }
}

.login-content {
  position: relative;
  z-index: 1;
  height: 100vh;
  padding: 0 48rpx;
}

.logo-section {
  padding-top: 120rpx;
  margin-bottom: 80rpx;

  .logo-wrapper {
    margin-bottom: 40rpx;

    .app-logo {
      width: 160rpx;
      height: 160rpx;
      border-radius: 32rpx;
      background-color: rgba(255, 255, 255, 0.9);
      padding: 20rpx;
    }
  }

  .app-title {
    font-size: 48rpx;
    font-weight: bold;
    color: white;
    margin-bottom: 16rpx;
  }

  .app-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.login-form {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 48rpx 40rpx;
  backdrop-filter: blur(10px);
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);

  .form-title {
    text-align: center;
    margin-bottom: 48rpx;

    .title-text {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 12rpx;
    }

    .subtitle-text {
      font-size: 26rpx;
      color: #666;
    }
  }

  .login-type-tabs {
    margin-bottom: 40rpx;

    .tabs-container {
      display: flex;
      background: #f0f2f5;
      border-radius: 8rpx;
      padding: 4rpx;
    }

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 16rpx 0;
      border-radius: 6rpx;
      transition: all 0.3s ease;
      cursor: pointer;

      &.active {
        background: #1890ff;

        .tab-text {
          color: white;
        }
      }
    }

    .tab-text {
      color: #666;
      font-size: 28rpx;
      font-weight: 500;
    }
  }

  .input-group {
    margin-bottom: 32rpx;

    .input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      background-color: #f8f9fa;
      border-radius: 12rpx;
      border: 2rpx solid transparent;
      transition: all 0.3s ease;

      &:focus-within {
        border-color: #1890ff;
        background-color: white;
        box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
      }

      .input-icon {
        font-size: 32rpx;
        color: #999;
        margin: 0 24rpx;
      }

      .form-input {
        flex: 1;
        height: 88rpx;
        font-size: 28rpx;
        color: #333;
        background: transparent;
        border: none;
        outline: none;
      }

      .password-toggle {
        font-size: 32rpx;
        color: #999;
        margin: 0 24rpx;
        cursor: pointer;
        transition: color 0.3s ease;

        &:hover {
          color: #1890ff;
        }
      }
    }
  }

  .error-message {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    padding: 16rpx 20rpx;
    background-color: #fff2f0;
    border-radius: 8rpx;
    border: 1rpx solid #ffccc7;

    .cuIcon-warn {
      font-size: 28rpx;
      color: #ff4d4f;
      margin-right: 12rpx;
    }

    .error-text {
      font-size: 26rpx;
      color: #ff4d4f;
    }
  }

  .login-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #1890ff, #096dd9);
    border: none;
    border-radius: 12rpx;
    color: white;
    font-size: 32rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    box-shadow: 0 4rpx 16rpx rgba(24, 144, 255, 0.3);

    &:not(:disabled):active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.3);
    }

    &:disabled {
      background: #d9d9d9;
      box-shadow: none;
      cursor: not-allowed;
    }

    &.loading {
      .cuIcon-loading2 {
        margin-right: 12rpx;
        animation: spin 1s linear infinite;
      }
    }
  }
}

.version-info {
  position: absolute;
  bottom: 60rpx;
  left: 0;
  right: 0;

  .version-text {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(60rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
